﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using Fluid;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZYing.LiquidThemeEngine.AspNetCore;
using ZYing.LiquidThemeEngine.FileProviders;
using ZYing.LiquidThemeEngine.MvcSample.Models;

namespace ZYing.LiquidThemeEngine.MvcSample.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly LiquidThemeEngineOptions _options;
        public HomeController(ILogger<HomeController> logger, IOptions<LiquidThemeEngineOptions> options)
        {
            _logger = logger;
            _options = options.Value;
        }

        public IActionResult Index()
        {
            Response.ContentType = "text/html; charset=UTF-8";
            var model = new
            {
                Id = 123,
                Age = 10,
                CreatedTime = DateTime.Now
            };
            var context = new LiquidThemeTemplateContext(_options, "default", model);
            context.SetValue("list", new[] { 1, 2, 3, 4, 5, 6 });
            var result = new LiquidThemeViewResult(context, "index");
            return result;
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        public async Task TestAsync()
        {
            //主题文件存放地址
            var themeRootPath = Path.GetFullPath(Path.Combine("wwwroot", "themes"));
            var fileProvider = new PhysicalFileProvider(themeRootPath);
            //主题引擎配置
            var themeEnginOptions = new LiquidThemeEngineOptions();
            themeEnginOptions.FileProvider = new LiquidThemeFileProvider(fileProvider);//配置主题文件所在的位置

            //主题名称（主题目录名称）
            var theme = "default";
            //视图名称，对应 templates 目录下的文件
            var view = "index";
            //视图模型，可以在模板中使用
            var model = new
            {
                Id = 123,
                Age = 10,
                CreatedTime = DateTime.Now
            };
            //创建一个模板上下文
            var context = new LiquidThemeTemplateContext(themeEnginOptions, theme, model);
            //设置多语言环境
            context.CultureInfo = new CultureInfo("zh-hans");
            //设置模板变量
            context.SetValue("title", "标题的取值");
            //渲染结果
            var html = await LiquidThemeViewRender.RenderAsync(theme, view, context);
            Console.WriteLine("渲染结果：{0}", html);
        }
    }
}